package com.yuanhe.yunoj.judge.codeSandbox;

import cn.hutool.json.JSONUtil;
import com.yuanhe.yunoj.common.ErrorCode;
import com.yuanhe.yunoj.exception.BusinessException;
import com.yuanhe.yunoj.judge.codeSandbox.model.ExecuteCodeRequest;
import com.yuanhe.yunoj.judge.codeSandbox.model.ExecuteCodeResponse;
import com.yuanhe.yunoj.judge.codeSandbox.strategy.JudgeContext;
import com.yuanhe.yunoj.model.dto.question.JudgeCase;
import com.yuanhe.yunoj.model.dto.questionsubmit.JudgeInfo;
import com.yuanhe.yunoj.model.entity.Question;
import com.yuanhe.yunoj.model.entity.QuestionSubmit;
import com.yuanhe.yunoj.model.enums.QuestionSubmitStatusEnum;
import com.yuanhe.yunoj.service.QuestionService;
import com.yuanhe.yunoj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {
    @Resource
    private QuestionSubmitService questionSubmitService;
    @Resource
    private QuestionService questionService;

    @Value("${codesandbox.type:example}")
    private String type;
    @Resource
    private JudgeManager judgeManager;

    @Override
    public QuestionSubmit dojudge(long questionSubmitId) {
        // 1.获取提交题目的所有信息
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        // 2.检查题目的提交状态 防止重复提交 如果题目提交状态为等待中才可以判题，不为等待中不行
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题中");
        }
        // 3.更改题目提交的状态为判题中 这一步是防止重复提交（代码沙箱执行判题可能很久，在没有返回结果之前如果用户在提交一次
        // 就会重复执行，更改状态防止重复）
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改题目状态失败");
        }
        // 4.执行代码沙箱
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);//把json字符串转换成java对象列表
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        // 5.根据沙箱的执行结果 设置题目的判题状态和信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(executeCodeResponse.getOutputList());
        judgeContext.setQuestion(question);
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfo = judgeManager.dojudge(judgeContext);
        // 6 修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionId);
        return questionSubmitResult;
    }
}
